package com.example.myblogserver.controller.img;

import io.swagger.annotations.Api;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api")
@Slf4j
@Api(tags = "图片相关接口")
public class ImgController {

    /**
     *  上传图片
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadImg(@RequestParam(value="myFileName") MultipartFile file, HttpServletRequest request) {
        String separator = System.getProperty("file.separator");
        separator=separator.replaceAll("\\\\","/");
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +    request.getContextPath()+ separator; //获取项目路径+端口号 比如：http://localhost:8181/
        try {
            String filePath="";
            //获取源文件
            filePath="/usr/local/web/imgUploads" ;//存储地址，此处也可以在application.yml中配置对象用@Value("${*.**}")注解注入内容
            String filename = file.getOriginalFilename();//获取图片名
            String[] names=filename.split("\\.");//获取后缀格式
            String uploadFileName= UUID.randomUUID().toString()+"."+names[names.length-1];//生成新图片
            File targetFile = new File(filePath,uploadFileName);//目标文件
            if (!targetFile.getParentFile().exists()){
                targetFile.getParentFile().mkdirs();
            }
            //传图片一步到位
            file.transferTo(targetFile);
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, String> data = new HashMap<>();
            data.put("url",basePath+"imgUploads/"+uploadFileName);//这里应该是项目路径，返回前台url
            map.put("code",1);
            map.put("msg","上传成功");
            map.put("data",data);
            //System.out.println(map.get("data"));
            return map;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("code", 0);
            errorResult.put("msg", "上传失败：" + e.getMessage());
            return errorResult;
        }
    }
}
